package com.chukun.concurrency.unthreadclass;

import com.chukun.concurrency.annotations.UnThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@UnThreadSafe
public class SimpleDateFormatOperator {

    private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    //并发线程总数
    private static final int totalThreadCount=1000;

    //允许同时访问的总数
    private static final int allowThreadCount = 200;

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(totalThreadCount);
        Semaphore semaphore = new Semaphore(allowThreadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<totalThreadCount;i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    parse();
                    semaphore.release();
                }catch (Exception e){
                    log.error("error count add ",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void parse(){
        try {
            /**
             * 多线程情况下会报错:
             * java.lang.NumberFormatException: For input string: ""
             * 线程不安全的类
             */
            dateFormat.parse("20181104");
        } catch (ParseException e) {
            log.error("parse error ",e);
        }
    }

}
